import { ISysArticleVm } from '/@/views/article/sysarticle/api/interface';

/**
 * 文章数据管理组合式API
 * 负责缓存和管理首页文章数据
 */
export function useArticleStore() {
  const CACHE_PREFIX = 'home_announcements';
  const CATEGORY_CACHE_KEY = 'home_categories';
  const CACHE_EXPIRY = 1 * 60 * 1000; // 1分钟缓存
  const CATEGORY_CACHE_EXPIRY = 30 * 60 * 1000; // 30分钟缓存

  // 生成缓存键
  function generateCacheKey(categoryType: string = 'all', maxCount: number = 5): string {
    return `${CACHE_PREFIX}_${categoryType}_${maxCount}`;
  }

  // 缓存文章数据
  function cacheArticles(articles: any[], cacheKey?: string) {
    const key = cacheKey || generateCacheKey();
    const cacheData = {
      timestamp: Date.now(),
      data: articles
    };
    sessionStorage.setItem(key, JSON.stringify(cacheData));
  }

  // 检查是否有有效缓存
  function hasCache(cacheKey?: string): boolean {
    const key = cacheKey || generateCacheKey();
    const cache = sessionStorage.getItem(key);
    if (!cache) return false;

    try {
      const { timestamp } = JSON.parse(cache);
      return Date.now() - timestamp < CACHE_EXPIRY;
    } catch {
      return false;
    }
  }

  // 获取缓存的文章数据
  function getCachedArticles(cacheKey?: string): any[] {
    const key = cacheKey || generateCacheKey();
    const cache = sessionStorage.getItem(key);
    if (!cache) return [];

    try {
      const { data } = JSON.parse(cache);
      return data;
    } catch {
      return [];
    }
  }

  // 缓存分类数据
  function cacheCategories(categories: any[]) {
    const cacheData = {
      timestamp: Date.now(),
      data: categories
    };
    sessionStorage.setItem(CATEGORY_CACHE_KEY, JSON.stringify(cacheData));
  }

  // 检查分类缓存是否有效
  function hasCategoryCache(): boolean {
    const cache = sessionStorage.getItem(CATEGORY_CACHE_KEY);
    if (!cache) return false;

    try {
      const { timestamp } = JSON.parse(cache);
      return Date.now() - timestamp < CATEGORY_CACHE_EXPIRY;
    } catch {
      return false;
    }
  }

  // 获取缓存的分类数据
  function getCachedCategories(): any[] {
    const cache = sessionStorage.getItem(CATEGORY_CACHE_KEY);
    if (!cache) return [];

    try {
      const { data } = JSON.parse(cache);
      return data;
    } catch {
      return [];
    }
  }

  // 清除缓存
  function clearCache(cacheKey?: string) {
    const key = cacheKey || generateCacheKey();
    sessionStorage.removeItem(key);
  }

  // 清除分类缓存
  function clearCategoryCache() {
    sessionStorage.removeItem(CATEGORY_CACHE_KEY);
  }

  // 清除所有相关缓存
  function clearAllCache() {
    const keys = Object.keys(sessionStorage);
    keys.forEach(key => {
      if (key.startsWith(CACHE_PREFIX) || key === CATEGORY_CACHE_KEY) {
        sessionStorage.removeItem(key);
      }
    });
  }

  return {
    cacheArticles,
    getCachedArticles,
    hasCache,
    cacheCategories,
    getCachedCategories,
    hasCategoryCache,
    clearCache,
    clearCategoryCache,
    clearAllCache,
    generateCacheKey,
  };
} 